<?php
namespace app\admin\controller;
use think\App;
use app\__MODULE__\model\{Card as CardModel,CardLog};
use app\common\BaseController;
use think\facade\Db;

// 卡片管理
class Card extends BaseController
{


    /**
     * 卡片列表
     * date 2021/3/16 10:32
     */
    public function card_list() {
        $page  = (int)request()->param('page', 1);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['name']) && $search['name'] !=''){
            $wheres[] = ['name','like',"%{$search['name']}%"];
        }
        $query  = CardModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        $redis = redis_instance();
        $type_map = [1=>'普通卡', 2=>'稀有卡'];
        foreach ($data as $key => $item) {
              // 卡片库存
              $item['number'] = $item['stock']==-1 ? '不限' : $redis->lLen("{$this->redis_key}:CardStock:{$item['id']}");
              $item['type_text'] = $type_map[$item['type']];
              // 总库存
              $item['stock_text'] = CardLog::where(['card_id'=>$item['id']])->count().'/'.($item['stock'] == -1 ? '不限' : $item['stock']);
              // 中奖次数
              $item['win_times_text'] = $item['win_times'] == -1 ? '不限次数' : '只中1次';
              // 每日库存
              $item['day_stock_text'] = CardLog::where(['card_id'=>$item['id'], 'log_date'=>date('Y-m-d')])->count().'/'.($item['day_stock'] == -1 ? '不限' : $item['day_stock']);

              //概率
              $item['ratio_text'] = round(100 * ($item['ratio'] / CardModel::sum('ratio')),2) .'%';
        }
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    /**
     * 添加卡片
     * date 2021/3/16 15:12
     */
    public function create() {
        $data = request()->post();
        try {
            $this->validate($data, [
                'name' => 'require',
            ], [
               'name.require'      => '名称必须',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
            if($data['type'] == 1) {
                $data['stock'] = $data['day_stock'] = -1;
            }
            $res = CardModel::create($data);
       
            // redis队列存入
            if(!empty($data['stock'])) {
                $redis = redis_instance();
                for($i=1; $i<=$data['stock']; $i++) {
                    $redis->lPush("{$this->redis_key}:CardStock:{$res->id}", 1);
                }
            }
            $res ? json_response(1, '添加成功') : json_response(0, '添加失败');
    }

    /**
     * 编辑卡片
     * date 2021/3/16 18:22
     */
    public function edit() {
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'name' => 'require',
            ], [
                'id.require'      => 'id必须',
               'name.require'      => '名称必须',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if($data['type'] == 1) {
            $data['stock'] = $data['day_stock'] = -1;
        }
        unset($data['type']);
        $res = CardModel::update($data);
        $res ? json_response(1, '编辑成功') : json_response(0, '编辑失败');
    }

    /**
     * 删除卡片
     * date 2021/3/17 17:30
     */
    public function delete() {
        $ids = param_check('ids');
        $res = CardModel::where('id', 'in',$ids)->delete();
        if($res) {
            $redis = redis_instance();
            $ids = explode(',', $ids);
            foreach ($ids as $key => $value) {
                $redis->del("{$this->redis_key}:CardStock:{$value}");
            }
           
            json_response(1, '删除成功');
        }else {
            json_response(0, '删除失败');
        }
    }

    /**
     * 上架/下架操作
     * date 2021/3/17 11:20
     */
    public function card_switch() {
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = db('card')->where('id', $id)->update([
            'status'        => $checked ? 1 : 0,
            'update_time'   => time()
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }

    /**
     * 添加库存
     * date 2021/4/11 17:36
     */
    public function add_stock() {
        $id = param_check('id');
        $stock = param_check('stock');
        $res = CardModel::where('id', $id)->update([
            'stock'         => ['INC', $stock],
            'update_time'   => time()
        ]);
        if($res) {
            $redis = redis_instance();
            for($i=1; $i<=$stock; $i++) {
                $redis->lPush("{$this->redis_key}:CardStock:{$id}", 1);
            }
            json_response(1, '添加库存成功');
        }else {
            json_response(0, '添加库存失败');
        }
    }


            /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = CardModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
    /**
     * 抽卡记录
     * date 2021/4/11 17:38
     */
    public function card_log() {
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $map = [];
        if(!empty($_REQUEST['card_id'])) $map[] = ['a.card_id', '=', $_REQUEST['card_id']];
        if(!empty($_REQUEST['user'])) $map[] = ['b.nickname|mobile', 'like', "%{$_REQUEST['user']}%"];
        $query = Db::name('card_log')
            ->alias('a')
            ->where($map)
            ->leftJoin('user b', 'a.user_id=b.id')
            ->field('a.*, b.nickname, b.avatar')
            ->order('a.id DESC');
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('a.id desc')->select()->toArray();

        $card = CardModel::field('id,name')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'card' =>  $card
        ]);
    }

        /**
     * 中奖记录导出
     * @return void
     * @author Sam
     * @date 2022-04-28
     */
    public function card_log_export(){
        $map = [];
        if(!empty($_REQUEST['card_id'])) $map[] = ['a.card_id', '=', $_REQUEST['card_id']];
        if(!empty($_REQUEST['user'])) $map[] = ['b.nickname|mobile', 'like', "%{$_REQUEST['user']}%"];
        $query = Db::name('card_log')
            ->alias('a')
            ->where($map)
            ->leftJoin('user b', 'a.user_id=b.id')
            ->field('a.*, b.nickname, b.avatar')
            ->order('a.id DESC');
            big_array_to_csv($query, '抽奖记录导出', [
                'prize_type'    => ['卡片类型', function($row) {
                    if($row['card_type'] == 1) return '普通卡';
                    if($row['card_type'] == 2) return '稀有卡';

                    return '';
                }],
                'card_name'    => '卡片名称',
                'nickname'          => '姓名',
                'log_time'      => ['中奖时间', 'datetime']
            ]);
    }
}